package com.lanp.springredis.listener;

import com.lanp.springredis.scv.RedisCSV;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.redisson.api.map.event.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Service;

/**
 * @author JiangPeng
 * Created with IntelliJ IDEA.
 * Description:  键值更新监听
 * Date: 2023-08-09 14:43:45
 */
@Service
public class MapCacheListener implements ApplicationRunner, Ordered {
    @Autowired
    private RedissonClient redisson;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("开始监听mapCache:" + RedisCSV.cmap_user.getKey());
        RMapCache<Object, Object> mapCache = redisson.getMapCache(RedisCSV.cmap_user.getKey());
        //元素增加监听
        mapCache.addListener(new EntryCreatedListener<String, Object>() {
            @Override
            public void onCreated(EntryEvent<String, Object> entryEvent) {
                System.out.println(RedisCSV.cmap_user.getKey() + "增加的键值key:" + entryEvent.getKey() + " value:" + entryEvent.getValue());
            }
        });
        //元素过期监听
        mapCache.addListener(new EntryExpiredListener<String, Object>() {
            @Override
            public void onExpired(EntryEvent<String, Object> entryEvent) {
                System.out.println(RedisCSV.cmap_user.getKey() + "过期的键值key:" + entryEvent.getKey() + " value:" + entryEvent.getValue());
            }
        });
        //元素删除监听
        mapCache.addListener(new EntryRemovedListener<String, Object>() {
            @Override
            public void onRemoved(EntryEvent<String, Object> entryEvent) {
                System.out.println(RedisCSV.cmap_user.getKey() + "删除的键值key:" + entryEvent.getKey() + " value:" + entryEvent.getValue());
            }
        });
        //元素更新监听
        mapCache.addListener(new EntryUpdatedListener<String, Object>() {
            @Override
            public void onUpdated(EntryEvent<String, Object> entryEvent) {
                System.out.println(RedisCSV.cmap_user.getKey() + "更新的键值key:" + entryEvent.getKey() + " value:" + entryEvent.getValue());
            }
        });
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
